package com.klxedu.ms.gateway.zullfilter;

import com.klxedu.ms.gateway.AuthServerConstants;
import com.klxedu.ms.gateway.TenancyConfiguration;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

import javax.servlet.http.HttpServletRequest;
import java.util.Base64;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.FORM_BODY_WRAPPER_FILTER_ORDER;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

public class AccessUserNameFilter extends ZuulFilter {

	@Override
	public Object run() {
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();
		String userID = (String) request.getSession().getAttribute(AuthServerConstants.SESSION_KEY_USERID);
		String name = (String) request.getSession().getAttribute(AuthServerConstants.SESSION_KEY_USERNAME);
		String loginID = (String) request.getSession().getAttribute(AuthServerConstants.SESSION_KEY_LOGINID);
		String departID = (String) request.getSession().getAttribute(AuthServerConstants.SESSION_KEY_DEPARTID);
		String scopeCode = (String) request.getSession().getAttribute(AuthServerConstants.SESSION_KEY_SCOPECODE);
		String unitScopeCode = (String) request.getSession().getAttribute(AuthServerConstants.SESSION_KEY_UNITSCOPECODE);
		String roles = (String) request.getSession().getAttribute(AuthServerConstants.SESSION_KEY_ROLES);
		String sessionID=request.getSession().getId();
		String base64Name = "";
		if (name != null && !"".equals(name)) {
			base64Name = Base64.getEncoder().encodeToString(name.getBytes());
		}
		ctx.addZuulRequestHeader(AuthServerConstants.SESSION_KEY_USERID, userID);
		ctx.addZuulRequestHeader(AuthServerConstants.SESSION_KEY_USERNAME, base64Name);
		ctx.addZuulRequestHeader(AuthServerConstants.SESSION_KEY_LOGINID, loginID);
		ctx.addZuulRequestHeader(AuthServerConstants.SESSION_KEY_DEPARTID, departID);
		ctx.addZuulRequestHeader(AuthServerConstants.SESSION_KEY_SCOPECODE, scopeCode);
		ctx.addZuulRequestHeader(AuthServerConstants.SESSION_KEY_UNITSCOPECODE, unitScopeCode);
		ctx.addZuulRequestHeader(AuthServerConstants.SESSION_KEY_ROLES, roles);
		ctx.addZuulRequestHeader(AuthServerConstants.SESSION_KEY_HOST, TenancyConfiguration.getTenancy());
		ctx.addZuulRequestHeader(AuthServerConstants.SESSION_KEY_ID, sessionID);
		return null;
	}

	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public int filterOrder() {
		return FORM_BODY_WRAPPER_FILTER_ORDER + 2;
	}

	@Override
	public String filterType() {
		return PRE_TYPE;
	}

}
